/**
* @File:app_init.c
* @Version:V1.0
* @Author:rudius
* @Brief:
* @Logs:
* 	Date		Author		Notes
* 	2025-07-14	rudius		first version
*/

// <<< Use Configuration Wizard in Context Menu >>>

/* Private includes --------------------------------------------------------- */
#include <rtthread.h>
#include <board.h>
#include <rtdevice.h>
#include "drv_spi.h"
#ifdef RT_USING_PIN
#include <drv_gpio.h>
#endif
#include "dev_spi_flash.h"
#include "dev_spi_flash_sfud.h"
#include <dfs_fs.h>
#ifdef __cplusplus
extern "C" {
#endif

/* Private config ----------------------------------------------------------- */
/* Private defines ---------------------------------------------------------- */
#define FLASH_NSS GET_PIN(B, 1)
/* Private typedef ---------------------------------------------------------- */
/* Private variables -------------------------------------------------------- */
/* Private function prototypes ---------------------------------------------- */

/*----------------------------------------------------------------------------*/
/* Private functions -------------------------------------------------------- */

/* Public functions --------------------------------------------------------- */
/**
 * @brief 
 * 
 * @return int 
 */
static int mnt_init(void)
{
    int ret = RT_EOK;

    /* 格式化文件系统 */
	dfs_mkfs("elm","W25Q128");//挂在前需格式化
    if(dfs_mount("W25Q128","/","elm",0,0)==0) //挂载文件系统，参数：块设备名称、挂载目录、文件系统类型、读写标志、私有数据0
    {
        rt_kprintf("dfs mount success\r\n");
        ret = RT_EOK;
    }
    else
    {
        rt_kprintf("dfs mount failed\r\n");
        ret = -RT_ERROR;
    }
    return ret;
}
INIT_ENV_EXPORT(mnt_init);

/**
 * @brief 
 * 
 * @return int 
 */
static int rt_hw_spi_flash_init(void)
{
    __HAL_RCC_GPIOB_CLK_ENABLE();
    struct rt_spi_configuration cfg;
    struct rt_spi_device *spi_dev;
	
	rt_hw_spi_device_attach("spi2", "spi20", FLASH_NSS);// spi20 表示挂载在 spi2 总线上的 0 号设备,PB1是片选，这一步就可以将从设备挂在到总线中。
    
	/* 步骤1：查找SPI设备（注意设备名应是挂载的SPI设备名，不是总线名） */
    spi_dev = (struct rt_spi_device *)rt_device_find("spi20");  // 改为实际挂载的设备名
    if (!spi_dev) {
        rt_kprintf("Error: SPI device not found!\n");
        return RT_ERROR;
    }

    if (RT_NULL == rt_sfud_flash_probe("W25Q128", "spi20"))  //注册块设备，这一步可以将外部flash抽象为系统的块设备
    {
        return -RT_ERROR;
    };

    return RT_EOK;
}
/* 导出到自动初始化 */
INIT_COMPONENT_EXPORT(rt_hw_spi_flash_init);

#ifdef __cplusplus
}
#endif
// <<< end of configuration section >>>
/* ----------------------------- end of app_init.c ---------------------------- */